package com.hk.pinda.authority.controller.auth;

import com.hk.pinda.authority.biz.service.auth.ValidateCodeService;
import com.hk.pinda.authority.biz.service.auth.impl.AuthManager;
import com.hk.pinda.authority.dto.auth.LoginDTO;
import com.hk.pinda.authority.dto.auth.LoginParamDTO;
import com.hk.pinda.base.BaseController;
import com.hk.pinda.base.BaseResult;
import com.hk.pinda.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 *
 *  登录（认证）控制器
 *
 */
@Api(tags = "登录控制器",value = "LoginController")
@RequestMapping("/anno")
@ResponseBody
@Controller
public class LoginController extends BaseController {

    @Autowired
    private ValidateCodeService validateCodeService;


    @Autowired
    private AuthManager authManager;

    /**
     *  为前端系统生成 验证码
     *
     * @param response
     */
    @GetMapping(value = "/captcha",produces = "image/png")
    @ApiOperation(notes = "验证码",value = "验证码")
    @SysLog(value = "生成验证码")
    public void captcha(HttpServletResponse response, @RequestParam(value = "key") String key) throws IOException {

        //
        validateCodeService.create(key,response);
    }

    @PostMapping("/login")
    @ApiOperation(notes = "登录", value = "登录")
    @SysLog(value = "登录")
    public BaseResult<LoginDTO> login(@Validated @RequestBody LoginParamDTO loginParamDTO){

        // 校验验证码是否正确
        boolean check = validateCodeService.check(loginParamDTO.getKey(),loginParamDTO.getCode());
        if(check){
            // 验证码校验通过， 执行具体的登录认证逻辑
            BaseResult<LoginDTO> result  = authManager.login(loginParamDTO.getAccount(),loginParamDTO.getPassword());

            return result;
        }

        // 验证码校验不通过，直接返回
        return this.success(null);
    }


    /**
     *  校验验证码
     *
     * @param loginParamDTO
     * @return
     */
    @PostMapping("/check")
    @ApiOperation(notes = "校验验证码", value = "校验验证码")
    public BaseResult<Boolean> check(@RequestBody LoginParamDTO loginParamDTO){
        Boolean result = validateCodeService.check(loginParamDTO.getKey(),loginParamDTO.getCode());
        return BaseResult.success(result);
    }


}
